package com.example.rest.service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.rest.model.ScoreModel;
import com.example.rest.model.UserModel2;

/**
 * @BelongsProject: RestTemplate
 * @BelongsPackage: com.example.rest.service
 * @Author:hlzs1
 * @Description: 描述什么人干什么事儿
 * @CreateTime: 2023-03-02 10:38
 * @Version: 1.0
 */
@Service
public class DeleteService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @description:restTemplate的Delete请求
     * @author: haolizhuo
     * @date: 2023/3/2
     * @param: []
     * @return: void
     **/
    public void delete(){
        String url ="http://localhost:8090/restTemplate/hello4/{1}";
        restTemplate.delete(url,"郝立琢的Delete请求");
    }

    /**
     * @description:查询csdn的博客质量分
     * @author: haolizhuo
     * @date: 2023/4/20
     * @param: []
     * @return: void
     **/
    public String csdn(UserModel2 userModel2){

        Integer blogNum = userModel2.getBlogNum();
        Integer pageNum = 100;

        Integer page = blogNum/pageNum + 1 ;
        List<ScoreModel> modelList = new ArrayList<>();
        for (int i = 1; i <= page; i++) {
            List<ScoreModel> scoreModels = csdnCheck(String.valueOf(i), userModel2.getUserId());
            modelList.addAll(scoreModels);
        }
        save(modelList, userModel2.getUserId());
        return "success";
    }

    public List<ScoreModel>  csdnCheck(String page,String userId){
        //首先查询所有的文章
        String url = "https://blog.csdn.net/community/home-api/v1/get-business-list?page="+page+"&size=500&businessType=blog&orderby=&noMore=false&year=&month=&username="+userId;
        System.out.println(url);
        JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
        LinkedHashMap data = (LinkedHashMap)forObject.get("data");
        ArrayList list = (ArrayList)data.get("list");

        List<String> urlList = new ArrayList<>();
        for (Object o : list) {
            LinkedHashMap one = (LinkedHashMap) o;
            urlList.add(String.valueOf(one.get("url")));
        }
//
//        //循环调用csdn接口查询所有的博客质量分
        String urlScore = "https://bizapi.csdn.net/trends/api/v1/get-article-score";
//
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("accept","application/json, text/plain, */*");
        headers.set("x-ca-key","203930474");
        headers.set("x-ca-nonce","22cd11a0-760a-45c1-8089-14e53123a852");
        headers.set("x-ca-signature","RaEczPkQ22Ep/k9/AI737gCtn8qX67CV/uGdhQiPIdQ=");
        headers.set("x-ca-signature-headers","x-ca-key,x-ca-nonce");
        headers.set("x-ca-signed-content-type","multipart/form-data");

        headers.setContentType(MediaType.MULTIPART_FORM_DATA);


        //调用接口获取数据
        List<ScoreModel> scoreModels = new ArrayList<>();
        for (String bkUrl : urlList) {
            MultiValueMap<String,String> requestBody = new LinkedMultiValueMap<>();
            requestBody.put("url", Collections.singletonList(bkUrl));
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

            URI uri = URI.create(urlScore);

            ResponseEntity<String> responseEntity = restTemplate.postForEntity(uri, requestEntity, String.class);
            JSONObject data1 = JSON.parseObject(responseEntity.getBody(),JSONObject.class) ;
            ScoreModel scoreModel = JSONObject.parseObject(data1.get("data").toString(),ScoreModel.class);
            scoreModels.add(scoreModel);
            System.out.println("名称:  "+scoreModel.getTitle() +"分数:   " + scoreModel.getScore() +"时间:  " + scoreModel.getPost_time());
        }
        return scoreModels;
    }

    //保存数据
    public void save(List<ScoreModel> scoreModels ,String userId){
        //创建Excel工作簿对象
        Workbook workbook = new XSSFWorkbook();
        String sheetName = "Sheet1";
        workbook.createSheet(sheetName);

        // 将数据写入工作表中
        int rowIndex = 0;
        Row row = workbook.getSheet(sheetName).createRow(rowIndex++);
        Cell cell1 = row.createCell(0);
        cell1.setCellValue("名称");
        Cell cell2 = row.createCell(1);
        cell2.setCellValue("成绩");
        Cell cell3 = row.createCell(2);
        cell3.setCellValue("时间");

        for (ScoreModel person : scoreModels) {
            row = workbook.getSheet(sheetName).createRow(rowIndex++);
            try {
                BeanUtils.setProperty(person, "title", person.getTitle());
                BeanUtils.setProperty(person, "score", person.getScore());
                BeanUtils.setProperty(person, "post_time", person.getPost_time());

                row.createCell(0).setCellValue(person.getTitle());
                row.createCell(1).setCellValue(person.getScore());
                row.createCell(2).setCellValue(person.getPost_time());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        // 保存 Excel 文件到本地磁盘
        try (FileOutputStream outputStream = new FileOutputStream("/ide/workspace/csdn/"+userId+".xlsx")) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
